<template>
	<div class="app-container">
		<el-form :model="filter" size="medium">
			<el-row :gutter="10">
				<el-col :span="4">
					<el-form-item label="所属市" label-width="60px">
						<el-select v-model="filter.city" multiple collapse-tags placeholder="请选择（默认全选）" clearable
							style="width: 100%;">
							<el-option v-for="city in cities" :label="city" :value="city">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="企业性质" label-width="80px">
						<el-cascader v-model="filter.nature" :options="natures" :props="props" collapse-tags
							placeholder="请选择（默认全选）" clearable style="width: 100%;">
						</el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="所属行业" label-width="80px">
						<el-cascader v-model="filter.industry" :options="industries" :props="props" collapse-tags
							placeholder="请选择（默认全选）" clearable style="width: 100%;">
						</el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="2" :offset="0" align="right">
					<el-button type="primary" @click="display" icon="el-icon-search" size="medium">查询</el-button>
				</el-col>
				<el-col :span="2" align="right">
					<el-button type="info" @click="resetFilter" icon="el-icon-refresh-left" size="medium">重置</el-button>
				</el-col>
			</el-row>
		</el-form>
		<div style="margin-top: 2%;">
			<v-chart class="chart" :option="option" autoresize />
			<div class="table">
				<el-table v-loading="listLoading" height="550px" stripe :data="showData" element-loading-text="Loading"
					border fit highlight-current-row :cell-style="{ padding: '5px 0' }">
					<el-table-column prop="place" label="所属地区" align="center"></el-table-column>
					<el-table-column prop="companyCnt" label="企业数量" align="center"></el-table-column>
					<el-table-column prop="proportion" label="企业数量占比" align="center"></el-table-column>
				</el-table>
				<el-pagination @size-change="changePageSize" @current-change="changeCurrentPage"
					:current-page="page.currentPage" :page-sizes="[10, 20, 50]" :page-size="page.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="page.totalItems">
				</el-pagination>
			</div>
		</div>
	</div>
</template>
  
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import {
	TitleComponent,
	TooltipComponent,
	LegendComponent,
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import { getIndustries, getNatures, getAllEnterpriseInfo, getAllFormList, getAllInvestigationInfo } from '@/api/province/dataVisualization';

use([
	CanvasRenderer,
	PieChart,
	TitleComponent,
	TooltipComponent,
	LegendComponent,
]);

export default ({
	data() {
		return {
			option: {
				title: {
					text: '区域企业数量占比图',
					top: '0%',
					left: '30%',
					textStyle: {
						fontSize: '30px'
					}
				},
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b} : {c} ({d}%)',
				},
				toolbox: {
					feature: {
						saveAsImage: {}
					},
					right: '10%'
				},
				legend: {
					orient: 'vertical',
					right: '5%',
					top: 'center',
					data: [],
				},
				series: [
					{
						name: '各市企业占比',
						type: 'pie',
						radius: '80%',
						center: ['45%', '55%'],
						data: [],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)',
							},
						},
					},
				],
			},

			filter: {
				city: '',
				nature: '',
				industry: ''
			},
			rawData: [],
			processedData: [],
			filteredData: [],
			showData: [],
			listLoading: true,
			roles: [],
			page: {
				currentPage: 1,
				pageSize: 20,
				totalItems: 0,
			},
			props: { multiple: true },
			cities: [],
			natures: getNatures(),
			industries: getIndustries()

		}
	},

	components: {
		VChart,
	},

	provide: {
		[THEME_KEY]: 'light',
	},

	methods: {
		resetFilter() {
			this.filter = {
				city: '',
				nature: '',
				industry: ''
			}
		},

		// tableRowClassName({ row, rowIndex }) {
		// 	return rowIndex % 2 == 1 ? 'odd-row': 'even-row';
		// },

		changePageSize(val) {
			this.page.pageSize = val;
			this.display();
		},

		changeCurrentPage(val) {
			this.page.currentPage = val;
			this.display();
		},

		filterData() {
			let showCities = [];
			let showIndustries = []
			let showNatures = []

			if (this.filter.city.length == 0) {
				showCities = this.cities;
			} else {
				showCities = this.filter.city;
			}

			if (this.filter.industry.length == 0) {
				this.industries.forEach(item_first => {
					item_first.children.forEach(item_second => {
						showIndustries.push(item_first.value + '/' + item_second.value);
					})
				})
			} else {
				this.filter.industry.forEach(item => {
					showIndustries.push(item.at(0) + '/' + item.at(1));
				})
			}

			if (this.filter.nature.length == 0) {
				this.natures.forEach(item_first => {
					item_first.children.forEach(item_second => {
						showNatures.push(item_first.value + '/' + item_second.value);
					})
				})
			} else {
				this.filter.nature.forEach(item => {
					showNatures.push(item.at(0) + '/' + item.at(1));
				})
			}

			
			showCities = new Set(showCities)
			showIndustries = new Set(showIndustries)
			showNatures = new Set(showNatures)

			// console.log(this.rawData)
			let companyCnt = new Map()
			for (let i = 0; i < this.rawData.length; i++) {
				const company = this.rawData[i];
				if (!showCities.has(company.companyCity) || !showIndustries.has(company.companyIndustry) || !showNatures.has(company.companyNature)) continue;
				if (companyCnt.has(company.companyCity)) {
					companyCnt.set(company.companyCity, companyCnt.get(company.companyCity) + 1)
				} else {
					companyCnt.set(company.companyCity, 1)
				}
			}

			this.processedData = Array()
			companyCnt.forEach((value, key) => {
				this.processedData.push({
					place: key,
					companyCnt: value,
					proportion: (100 * value / this.rawData.length).toFixed(1) + '%'
				})
			})
			// console.log(this.processedData)

			this.page.totalItems = this.processedData.length
		},

		display() {
			this.listLoading = true
			this.filterData()
			let showCities = [];
			let seriesData = [];
			this.processedData.forEach(item => {
				seriesData.push({
					value: item.companyCnt,
					name: item.place
				})
				showCities.push(item.place)
			})
			this.option.legend.data = showCities
			this.option.series = [{
				name: '各市企业占比',
				type: 'pie',
				radius: '75%',
				center: ['45%', '55%'],
				data: seriesData,
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)',
					},
				},
			},
			]

			this.showData = this.processedData.slice((this.page.currentPage - 1) * this.page.pageSize, Math.min(this.page.totalItems, this.page.currentPage * this.page.pageSize))
			this.showData = this.showData.sort((a, b) => b.companyCnt - a.companyCnt)
			this.listLoading = false
		},

		fatchData() {
			getAllEnterpriseInfo({}).then(response => {
				// console.log(response)
				this.rawData = response.data;
				this.cities = Array.from(new Set(this.rawData.map(item => item.companyCity)));
				this.display();
			})
		}
	},


	created() {
		this.listLoading = true
		this.fatchData();
	}
});
</script>
  
<style scoped>
.chart {
	height: 600px;
	width: 65%;
	float: left;
}

.table {
	float: left;
	width: 35%;
}
</style>